/**
 * 
 */
package com.geekteam.geometrychess.handler.event;

import com.geekteam.geometrychess.database.DataAccessor;
import com.geekteam.geometrychess.utils.Code;
import com.geekteam.geometrychess.utils.Message;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;

/**
 * @author MtRol
 *
 */
public class LoginEventHandler extends BaseServerEventHandler{

	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		String username = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
		String password = (String) event.getParameter(SFSEventParam.LOGIN_PASSWORD);
		
		trace("Login to server. UserName: "+username+", Password: "+password);
		int code = DataAccessor.getInstance().checkLogin(username, password);
		if(code==Code.USER_NOT_FOUND){
			SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
			errorData.addParameter(username);
			throw new SFSException(Message.USER_NOT_FOUND, errorData);
		}else if(code==Code.INVALID_PASSWORD){
			SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
			errorData.addParameter(username);
			throw new SFSException(Message.INVALID_PASSWORD, errorData);
		}else if(code==Code.USER_NULL){
			SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_GUEST_NOT_ALLOWED);
			throw new SFSException(Message.USER_NULL, errorData);
		}else if(code==Code.PASS_NULL){
			SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_GUEST_NOT_ALLOWED);
			throw new SFSException(Message.PASS_NULL, errorData);
		}else if(code == Code.SUCCESS){
			trace("Login success");
		}else{
			SFSErrorData errorData = new SFSErrorData(SFSErrorCode.LOGIN_GUEST_NOT_ALLOWED);
			throw new SFSException(Message.UNKNOW_ERROR, errorData);
		}
	}

	
}
